import store from '@/store'
import router, { asyncRoutes } from '@/router'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  const userInfo = store.state.user.userInfo
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (Object.keys(userInfo).length <= 0) {
        const { roles: { menus }} = await store.dispatch('user/getUserProfile')
        console.log(menus)
        let otherRoutes = asyncRoutes.filter(item => menus.includes(item.children[0].name))
        otherRoutes = [...otherRoutes, { path: '*', redirect: '/404', hidden: true }]
        store.commit('permission/setRoutes', otherRoutes)

        router.addRoutes(otherRoutes)
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
        return
      }

      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach((to, from) => {
  NProgress.done()
})
